#!/bin/bash

# Development script for RINT Data Manager
# This script sets up the required environment and starts the server with auto-reload

echo "🚀 Starting RINT Data Manager development server..."
echo "📝 Setting up environment..."

# Set DATABASE_URL for SQLx compile-time query verification
export DATABASE_URL="sqlite:./rint_data_manager.db"

# Extract database file path from DATABASE_URL
DB_FILE="${DATABASE_URL#sqlite:}"

# Create database file if it doesn't exist
if [ ! -f "$DB_FILE" ]; then
    echo "📄 Creating database file: $DB_FILE"
    touch "$DB_FILE"
fi

# Check if database is already initialized
if [ -f "$DB_FILE" ] && [ -s "$DB_FILE" ]; then
    # Check if the database has been initialized by looking for known tables
    if sqlite3 "$DB_FILE" "SELECT name FROM sqlite_master WHERE type='table' AND name='users';" 2>/dev/null | grep -q "users"; then
        echo "✅ Database already initialized"
    else
        echo "🗄️ Database exists but needs initialization..."
        RUN_MIGRATIONS=true
    fi
else
    echo "🗄️ New database detected..."
    RUN_MIGRATIONS=true
fi

# Run database migrations to create tables if needed
if [ "$RUN_MIGRATIONS" = true ]; then
    echo "🗄️ Running database migrations..."

    # First, ensure the application compiles
    echo "🔨 Building application..."
    cargo build --quiet

    # Run migrations by starting the application briefly
    echo "🔄 Running migration script..."
    timeout 15s cargo run 2>&1 | {
        if grep -q "migration\|Migrator\|Running migrations"; then
            echo "✅ Database migrations completed"
        elif grep -q "error\|Error\|failed"; then
            echo "❌ Migration failed - check logs above"
            exit 1
        else
            echo "✅ Database appears to be ready"
        fi
    }
fi

# Create a default admin user if no users exist
echo "👤 Checking for default admin user..."

# Check if users table exists and has any users
if [ -f "$DB_FILE" ] && sqlite3 "$DB_FILE" "SELECT COUNT(*) FROM users;" 2>/dev/null | grep -q "^0$"; then
    echo "🔧 No users found. Creating default admin user..."

    # Create a simple curl script to register admin user
    cat > /tmp/create_admin.sh << 'EOF'
#!/bin/bash
# Script to create default admin user
EMAIL="admin@example.com"
PASSWORD="admin123"

echo "📧 Creating admin user: $EMAIL"
echo "🔑 Password: $PASSWORD"
echo ""

# Try to register the admin user
curl -s -X POST "http://localhost:$RINT_SERVER_PORT/api/register-admin" \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$EMAIL\",
    \"password\": \"$PASSWORD\"
  }" | jq -r '.email // .detail // "Failed to create admin user"' 2>/dev/null || echo "⚠️ Server not ready yet"
EOF

    chmod +x /tmp/create_admin.sh

    echo "💡 To create the admin user manually after server starts:"
    echo "   1. Open http://localhost:$RINT_SERVER_PORT in your browser"
    echo "   2. Go to registration page"
    echo "   3. Use these credentials or create your own:"
    echo "      Email: admin@example.com"
    echo "      Password: admin123"
    echo ""
    echo "📝 Or use curl command:"
    echo "   curl -X POST http://localhost:$RINT_SERVER_PORT/api/register-admin \\"
    echo "     -H \"Content-Type: application/json\" \\"
    echo "     -d '{\"email\":\"admin@example.com\",\"password\":\"admin123\"}'"
    echo ""
else
    echo "✅ Users already exist in database"
fi

# Test if the application can start successfully
echo "🧪 Testing application startup..."
timeout 5s cargo run 2>/dev/null | {
    if grep -q "Server\|listening\|Starting"; then
        echo "✅ Application starts successfully"
    elif grep -q "migration\|Migrator"; then
        echo "✅ Migrations completed, application ready"
    else
        echo "✅ Application appears ready"
    fi
}

# Set default port if not set
if [ -z "$RINT_SERVER_PORT" ]; then
    export RINT_SERVER_PORT="8383"
fi

# Optional: Enable debug logging
export RUST_LOG="info,rdm_rust=debug"

echo "✅ Environment configured"
echo "🔄 Starting server with auto-reload (cargo watch)..."
echo "📍 Server will be available at: http://0.0.0.0:$RINT_SERVER_PORT"
echo "🌐 Web interface: http://localhost:$RINT_SERVER_PORT"
echo "⏹️  Press Ctrl+C to stop"
echo ""
# If no users exist, create a helper script for admin setup
if [ -f "$DB_FILE" ] && sqlite3 "$DB_FILE" "SELECT COUNT(*) FROM users;" 2>/dev/null | grep -q "^0$"; then
    echo ""
    echo "🚨 NO USERS FOUND!"
    echo "   After the server starts, create an admin user by running:"
    echo "   curl -X POST http://localhost:$RINT_SERVER_PORT/api/register-admin \\"
    echo "     -H \"Content-Type: application/json\" \\"
    echo "     -d '{\"email\":\"admin@example.com\",\"password\":\"admin123\"}'"
    echo ""
    echo "   Or open http://localhost:$RINT_SERVER_PORT and register manually"
    echo "   (The first user automatically becomes admin)"
    echo ""

    # Create a helper script for admin user creation
    cat > create_admin_user.sh << 'EOF'
#!/bin/bash
# Helper script to create the first admin user
# Run this after the server has started

EMAIL="admin@example.com"
PASSWORD="admin123"
PORT="${RINT_SERVER_PORT:-8383}"

echo "🔧 Creating admin user..."
echo "📧 Email: $EMAIL"
echo "🔑 Password: $PASSWORD"
echo ""

# Wait for server to be ready
echo "⏳ Waiting for server to start..."
for i in {1..30}; do
    if curl -s "http://localhost:$PORT/api/config" > /dev/null 2>&1; then
        echo "✅ Server is ready!"
        break
    fi
    sleep 1
done

# Create admin user
echo "🔨 Creating admin user..."
RESPONSE=$(curl -s -X POST "http://localhost:$PORT/api/register-admin" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\"}")

if echo "$RESPONSE" | grep -q "email"; then
    echo "✅ Admin user created successfully!"
    echo "📧 Email: $EMAIL"
    echo "🔑 Password: $PASSWORD"
    echo ""
    echo "🌐 You can now login at: http://localhost:$PORT"
else
    echo "❌ Failed to create admin user"
    echo "Response: $RESPONSE"
    echo ""
    echo "💡 Try creating the user manually through the web interface:"
    echo "   http://localhost:$PORT"
fi
EOF
    chmod +x create_admin_user.sh
    echo "📝 Helper script created: ./create_admin_user.sh"
    echo "   Run it after the server starts to create the admin user"
    echo ""
else
    echo "💡 Users already exist in database."
    echo ""
    echo "👤 Available test users:"
    echo "   - alice@hillstonenet.com (password: alice123)"
    echo "   - bob@hillstonenet.com (password: bob123)"
    echo "   - admin@hillstonenet.com (password: admin123) [ADMIN]"
    echo "   - test@hillstonenet.com (password: test123)"
    echo "   - pytest@hillstonenet.com (password: pytest123)"
    echo ""
    echo "🌐 Login at: http://localhost:$RINT_SERVER_PORT"
    echo ""
fi

# Check if cargo-watch is installed
if ! command -v cargo-watch &> /dev/null; then
    echo "❌ cargo-watch not found. Installing..."
    cargo install cargo-watch
fi

# Start the development server with auto-reload
cargo watch -x run
